package com.example.wemedia.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.constants.NewsMessageConstants;
import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.model.wemedia.dto.NewsDto;
import com.example.model.wemedia.dto.NewsPageReqDto;
import com.example.model.wemedia.pojo.News;
import com.example.utils.thread.UserThreadLocal;
import com.example.wemedia.service.NewsAutoScanService;
import com.example.wemedia.service.NewsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Tag(name = "新闻管理信息")
@RestController
@RequestMapping("/api/v1")
public class NewsController  {
    @Autowired
    private NewsService newsService;
    @Autowired
    private NewsAutoScanService newsAutoScanService;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @PostMapping(value = "/news/getNewsPageQuery/{page}/{pageSize}")
    @Operation(summary = "新闻模糊查询分页")
    public R getNewsPageQuery(@RequestBody NewsPageReqDto newsPageReqDto, @PathVariable(value = "page") Long page, @PathVariable(value = "pageSize") Long pageSize) {
        //检查参数
        if (newsPageReqDto == null) {
            return R.error(ResultCodeRecord.PARAM_INVALID);
        }
        // 获取当前登录人的信息
        // 分页功能进行查询
        Page< News > materialPage = new Page<>(page, pageSize);
        // 条件构造器
        LambdaQueryWrapper< News > wrapper = new LambdaQueryWrapper<>();
        // 状态精确查询
        if (newsPageReqDto.getStatus() != null) {
            wrapper.eq(News::getNewsStatus, newsPageReqDto.getStatus());
        }
        // 频道精确查询
        if (newsPageReqDto.getChannelId() != null) {
            wrapper.between(News::getPublishTime, newsPageReqDto.getBeginPubDate(), newsPageReqDto.getEndPubDate());
        }
        // 关键字模糊查询
        if (StringUtils.isNotBlank(newsPageReqDto.getKeyword())) {
            wrapper.like(News::getNewsTitle, newsPageReqDto.getKeyword());
        }
        wrapper.eq(News::getUserId, UserThreadLocal.getUser().getUserId());
        // 按时间倒序
        wrapper.orderByAsc(News::getCreatedTime);
        // 查询数据
        newsService.page(materialPage, wrapper);
        // 每页的数据集合
        List< News > newsList = materialPage.getRecords();
        // 总的记录数
        Long total = materialPage.getTotal();
        // 每页条数
        Long size = materialPage.getSize();
        // 总页数
        Long pages = materialPage.getPages();
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("pageSize", size);
        map.put("pages", pages);
        map.put("page", page);
        map.put("newsList", newsList);
        if (map != null) {
            return R.ok("查询模糊新闻分页成功").data(map);
        } else {
            return R.error("查询模糊新闻分页失败");
        }
    }

    @PostMapping(value = "/news/addNews")
    @Operation(summary = "增加新闻")
    public R addNews(@RequestBody NewsDto newsDto) {
        // 校验
        if (StringUtils.isEmpty(newsDto.getTitle()) || StringUtils.isEmpty(newsDto.getContent())) {
            return R.error(ResultCodeRecord.PARAM_REQUIRE);
        }
        // 获取内容中的图片
        List<String> contentImages = newsService.getContentImages(newsDto);
        News news = newsService.saveOrUpdate(newsDto, contentImages);
        boolean flag = newsAutoScanService.autoScan(news);
        // 别忘记这种代码解决问题
        if (flag && newsDto.getStatus() == News.NewsStatus.NORMAL.getCode()) {
            return R.ok("增加新闻成功");
        } else {
            return R.error("增加新闻失败");
        }
    }

    @PutMapping("/news/downOrUpNews")
    @Operation(summary = "文章的上下架")
    public R downOrUpNews(@RequestBody NewsDto newsDto) {
        // 1、检查参数
        if (newsDto.getId() == null) {
            return R.error(ResultCodeRecord.PARAM_INVALID);
        }
        // 2、查询文章
        News news = newsService.getById(newsDto.getId());
        if (news == null) {
            return R.error(ResultCodeRecord.DATA_NOT_EXIST);
        }
        // 3、判断文章是否已发布
        if (news.getNewsStatus().equals(News.NewsStatus.PUBLISHED.getCode())) {
            return R.error("当前文章不是发布状态，不能上下架");
        }
        // 4、修改文章enable
        if (newsDto.getEnable() != null && newsDto.getEnable() > -1 && newsDto.getEnable() < 2) {
            QueryWrapper<News> wrapper = new QueryWrapper<>();
            wrapper.eq("id", newsDto.getId());
            News updateNews = new News();
            updateNews.setNewsEnable(newsDto.getEnable());
            newsService.update(updateNews, wrapper);
            if (news.getArticleId() != null) {
                // 发送消息，通知article文章的配置
                Map<String, Object> map = new HashMap<>();
                map.put("articleId", news.getArticleId());
                map.put("enable", newsDto.getEnable());
                kafkaTemplate.send(NewsMessageConstants.NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }
            return R.ok("修改文章状态成功");
        } else {
            return R.error("修改文章状态失败");
        }
    }

    /*@GetMapping("/getInfo/{id}")
    @Operation(summary = "按照ID编号查看")
    public ResultBean<News> selectOne(@PathVariable Serializable id) {
        return ResultBean.success(this.newsService.getById(id));
    }

    @PutMapping("/update")
    @Operation(summary = "修改News")
    public ResultBean update(@RequestBody News news) {
        this.newsService.updateById(news);
        return ResultBean.success();
    }

    @DeleteMapping("/remove")
    @Operation(summary = "删除News")
    public ResultBean delete(@RequestParam("idList") List<Long> idList) {
        this.newsService.removeByIds(idList);
        return ResultBean.success();
    }*/
}

